package com.train.webadmin.app.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.train.common.log.annotation.OperationLog;
import com.train.common.log.model.constant.SysOperationLogType;
import com.github.pagehelper.page.PageMethod;
import com.train.webadmin.app.util.LongitudeAndLatitudeToAddress;
import com.train.webadmin.app.util.QRcodeUtil;
import com.train.webadmin.app.vo.*;
import com.train.webadmin.app.dto.*;
import com.train.webadmin.app.model.*;
import com.train.webadmin.app.service.*;
import com.train.common.core.object.*;
import com.train.common.core.util.*;
import com.train.common.core.constant.*;
import com.train.common.core.annotation.MyRequestBody;
import com.train.webadmin.config.ApplicationConfig;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 学生签到操作控制器类。
 *
 * @author xulei
 * @date 2025-03-07
 */
@Tag(name = "学生签到管理接口")
@Slf4j
@RestController
@RequestMapping("/admin/app/studentSignIn")
public class StudentSignInController {

    @Autowired
    private ApplicationConfig appConfig;
    @Autowired
    private StudentSignInService studentSignInService;
    @Autowired
    private CourseInfoService courseInfoService;
    @Autowired
    private StudentInfoService studentInfoService;
    @Autowired
    private ClassInfoService classInfoService;
    @Autowired
    private ProfessorInfoService professorInfoService;
    @Autowired
    private TeacherInfoService teacherInfoService;
    @Autowired
    private ClassStudentService classStudentService;

    /**
     * 新增学生签到数据。
     *
     * @param studentSignInDto 新增对象。
     * @return 应答结果对象，包含新增对象主键Id。
     */
    @ApiOperationSupport(ignoreParameters = {
            "studentSignInDto.id",
            "studentSignInDto.searchString",
            "studentSignInDto.signInTimeStart",
            "studentSignInDto.signInTimeEnd"})
    @SaCheckPermission("studentSignIn.add")
    @OperationLog(type = SysOperationLogType.ADD)
    @PostMapping("/add")
    public ResponseResult<Long> add(@MyRequestBody StudentSignInDto studentSignInDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(studentSignInDto, false);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        StudentSignIn studentSignIn = MyModelUtil.copyTo(studentSignInDto, StudentSignIn.class);
        studentSignIn = studentSignInService.saveNew(studentSignIn);
        return ResponseResult.success(studentSignIn.getId());
    }

    /**
     * 更新学生签到数据。
     *
     * @param studentSignInDto 更新对象。
     * @return 应答结果对象。
     */
    @ApiOperationSupport(ignoreParameters = {
            "studentSignInDto.searchString",
            "studentSignInDto.signInTimeStart",
            "studentSignInDto.signInTimeEnd"})
    @SaCheckPermission("studentSignIn.update")
    @OperationLog(type = SysOperationLogType.UPDATE)
    @PostMapping("/update")
    public ResponseResult<Void> update(@MyRequestBody StudentSignInDto studentSignInDto) {
        String errorMessage = MyCommonUtil.getModelValidationError(studentSignInDto, true);
        if (errorMessage != null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_VALIDATED_FAILED, errorMessage);
        }
        StudentSignIn studentSignIn = MyModelUtil.copyTo(studentSignInDto, StudentSignIn.class);
        StudentSignIn originalStudentSignIn = studentSignInService.getById(studentSignIn.getId());
        if (originalStudentSignIn == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [数据] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!studentSignInService.update(studentSignIn, originalStudentSignIn)) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.success();
    }

    /**
     * 删除学生签到数据。
     *
     * @param id 删除对象主键Id。
     * @return 应答结果对象。
     */
    @SaCheckPermission("studentSignIn.delete")
    @OperationLog(type = SysOperationLogType.DELETE)
    @PostMapping("/delete")
    public ResponseResult<Void> delete(@MyRequestBody Long id) {
        if (MyCommonUtil.existBlankArgument(id)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        return this.doDelete(id);
    }

    /**
     * 批量删除学生签到数据。
     *
     * @param idList 待删除对象的主键Id列表。
     * @return 应答结果对象。
     */
    @SaCheckPermission("studentSignIn.delete")
    @OperationLog(type = SysOperationLogType.DELETE_BATCH)
    @PostMapping("/deleteBatch")
    public ResponseResult<Void> deleteBatch(@MyRequestBody List<Long> idList) {
        if (MyCommonUtil.existBlankArgument(idList)) {
            return ResponseResult.error(ErrorCodeEnum.ARGUMENT_NULL_EXIST);
        }
        for (Long id : idList) {
            ResponseResult<Void> responseResult = this.doDelete(id);
            if (!responseResult.isSuccess()) {
                return responseResult;
            }
        }
        return ResponseResult.success();
    }

    /**
     * 列出符合过滤条件的学生签到列表。
     *
     * @param studentSignInDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @param pageParam 分页参数。
     * @return 应答结果对象，包含查询结果集。
     */
    @SaCheckPermission("studentSignIn.view")
    @PostMapping("/list")
    public ResponseResult<MyPageData<StudentSignInVo>> list(
            @MyRequestBody StudentSignInDto studentSignInDtoFilter,
            @MyRequestBody MyOrderParam orderParam,
            @MyRequestBody MyPageParam pageParam) {
        if (pageParam != null) {
            PageMethod.startPage(pageParam.getPageNum(), pageParam.getPageSize(), pageParam.getCount());
        }
        StudentSignIn studentSignInFilter = MyModelUtil.copyTo(studentSignInDtoFilter, StudentSignIn.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, StudentSignIn.class);
        List<StudentSignIn> studentSignInList =
                studentSignInService.getStudentSignInListWithRelation(studentSignInFilter, orderBy);
        return ResponseResult.success(MyPageUtil.makeResponseData(studentSignInList, StudentSignInVo.class));
    }

    /**
     * 导入主表数据列表。
     *
     * @param importFile 上传的文件，目前仅仅支持xlsx和xls两种格式。
     * @return 应答结果对象。
     */
    @SaCheckPermission("studentSignIn.import")
    @OperationLog(type = SysOperationLogType.IMPORT)
    @PostMapping("/import")
    public ResponseResult<Void> importBatch(
            @RequestParam Boolean skipHeader,
            @RequestParam("importFile") MultipartFile importFile) throws IOException {
        String filename = ImportUtil.saveImportFile(appConfig.getUploadFileBaseDir(), null, importFile);
        // 这里可以指定需要忽略导入的字段集合。如创建时间、创建人、更新时间、更新人、主键Id和逻辑删除，
        // 以及一些存在缺省值且无需导入的字段。其中主键字段和逻辑删除字段不需要在这里设置，批量插入逻辑会自动处理的。
        Set<String> ignoreFieldSet = new HashSet<>();
        ignoreFieldSet.add("updateTime");
        ignoreFieldSet.add("updateUserId");
        ignoreFieldSet.add("createTime");
        ignoreFieldSet.add("createUserId");
        List<ImportUtil.ImportHeaderInfo> headerInfoList = ImportUtil.makeHeaderInfoList(StudentSignIn.class, ignoreFieldSet);
        // 下面是导入时需要注意的地方，如果我们缺省生成的代码，与实际情况存在差异，请手动修改。
        // 1. 头信息数据字段，我们只是根据当前的主表实体对象生成了缺省数组，开发者可根据实际情况，对headerInfoList进行修改。
        ImportUtil.ImportHeaderInfo[] headerInfos = headerInfoList.toArray(new ImportUtil.ImportHeaderInfo[]{});
        // 2. 这里需要根据实际情况决定，导入文件中第一行是否为中文头信息，如果是可以跳过。这里我们默认为true。
        // 这里根据自己的实际需求，为doImport的最后一个参数，传递需要进行字典转换的字段集合。
        // 注意，集合中包含需要翻译的Java字段名，如: gradeId。
        Set<String> translatedDictFieldSet = new HashSet<>();
        List<StudentSignIn> dataList =
                ImportUtil.doImport(headerInfos, skipHeader, filename, StudentSignIn.class, translatedDictFieldSet);
        CallResult result = studentSignInService.verifyImportList(dataList, translatedDictFieldSet);
        if (!result.isSuccess()) {
            // result中返回了具体的验证失败对象，如果需要返回更加详细的错误，可根据实际情况手动修改。
            return ResponseResult.errorFrom(result);
        }
        //TODO: 下面方法的第二个字段列表参数，用于判断导入的数据在数据表是否已经存在，存在则更新，否则插入，如全部新数据，则无需任何修改。
        studentSignInService.saveNewOrUpdateBatch(dataList, CollUtil.newArrayList(), -1);
        return ResponseResult.success();
    }

    /**
     * 导出符合过滤条件的学生签到列表。
     *
     * @param studentSignInDtoFilter 过滤对象。
     * @param orderParam 排序参数。
     * @throws IOException 文件读写失败。
     */
    @SaCheckPermission("studentSignIn.export")
    @OperationLog(type = SysOperationLogType.EXPORT, saveResponse = false)
    @PostMapping("/export")
    public void export(
            @MyRequestBody StudentSignInDto studentSignInDtoFilter,
            @MyRequestBody MyOrderParam orderParam) throws IOException {
        StudentSignIn studentSignInFilter = MyModelUtil.copyTo(studentSignInDtoFilter, StudentSignIn.class);
        String orderBy = MyOrderParam.buildOrderBy(orderParam, StudentSignIn.class);
        List<StudentSignIn> resultList =
                studentSignInService.getStudentSignInListWithRelation(studentSignInFilter, orderBy);
        // 导出文件的标题数组
        // NOTE: 下面的代码中仅仅导出了主表数据，主表聚合计算数据和主表关联字典的数据。
        // 一对一从表数据的导出，可根据需要自行添加。如：headerMap.put("slaveFieldName.xxxField", "标题名称")
        Map<String, String> headerMap = new LinkedHashMap<>(12);
        headerMap.put("id", "id");
        headerMap.put("teacherId", "老师id");
        headerMap.put("classId", "班级Id");
        headerMap.put("classCode", "班级code");
        headerMap.put("studentId", "学生id");
        headerMap.put("courseId", "课程id");
        headerMap.put("signInTime", "签到时间");
        headerMap.put("signInAddress", "签到地址");
        headerMap.put("updateTime", "修改时间");
        headerMap.put("updateUserId", "修改用户id");
        headerMap.put("createTime", "创建时间");
        headerMap.put("createUserId", "创建人");
        ExportUtil.doExport(resultList, headerMap, "studentSignIn.xlsx");
    }

    /**
     * 查看指定学生签到对象详情。
     *
     * @param id 指定对象主键Id。
     * @return 应答结果对象，包含对象详情。
     */
    @SaCheckPermission("studentSignIn.view")
    @GetMapping("/view")
    public ResponseResult<StudentSignInVo> view(@RequestParam Long id) {
        StudentSignIn studentSignIn = studentSignInService.getByIdWithRelation(id, MyRelationParam.full());
        if (studentSignIn == null) {
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST);
        }
        StudentSignInVo studentSignInVo = MyModelUtil.copyTo(studentSignIn, StudentSignInVo.class);
        return ResponseResult.success(studentSignInVo);
    }

    private ResponseResult<Void> doDelete(Long id) {
        String errorMessage;
        // 验证关联Id的数据合法性
        StudentSignIn originalStudentSignIn = studentSignInService.getById(id);
        if (originalStudentSignIn == null) {
            // NOTE: 修改下面方括号中的话述
            errorMessage = "数据验证失败，当前 [对象] 并不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        if (!studentSignInService.remove(id)) {
            errorMessage = "数据操作失败，删除的对象不存在，请刷新后重试！";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        return ResponseResult.success();
    }

    @PostMapping("/QRcode/create")
    public ResponseResult<String> QRcodeCreate(@MyRequestBody StudentSignInDto studentSignInDto) throws Exception {
        TokenData tokenData = TokenData.takeFromRequest();
        TeacherInfo teacherInfo = teacherInfoService.getTeacherInfoByUserId(tokenData.getUserId());
        return ResponseResult.success(QRcodeUtil.byteToBase64(studentSignInDto.getClassId(), studentSignInDto.getCourseId(), teacherInfo.getId()));
    }

    @PostMapping("/sign/in")
    // 扫码签到 回调地址
    public ResponseResult<Long> signIn(@MyRequestBody StudentSignInDto studentSignInDto) {
        String errorMessage;
        TokenData tokenData = TokenData.takeFromRequest();
        StudentInfo studentInfo = studentInfoService.getStudentInfoByUserId(tokenData.getUserId());
        if (studentInfo == null) {
            errorMessage = "未查询到学员信息";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }

        if (studentInfo.getClassId() != studentSignInDto.getClassId()) {
            errorMessage = "您不是当前班级学员，无法进行扫码";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        Long expirationTime = studentSignInDto.getExpirationTime().getTime();
        String nowTime = String.valueOf(new Date().getTime());
        Long getNowTime = Long.valueOf(nowTime.substring(0, nowTime.length() - 3));
        Long courseId = studentSignInDto.getCourseId();
        CourseInfo courseInfo = courseInfoService.getById(studentSignInDto.getCourseId());
        if (new Date().getTime() > courseInfo.getQuittingTime().getTime()) {
            errorMessage = "当前课程已结束，无法进行签到";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        StudentSignIn lastSignIn = studentSignInService.getLastDateByStudentId(studentInfo.getId(), courseId);
        if (lastSignIn != null) {
            errorMessage = "您已经签到过了，请勿重复签到";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }

        if (getNowTime >= expirationTime) {
            errorMessage = "当前二维码已过期，请重新获取";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        Long classId = studentSignInDto.getClassId();
        ClassInfo classInfo = classInfoService.getById(classId);
        StudentSignIn studentSignIn = new StudentSignIn();
        studentSignIn.setTeacherId(studentSignInDto.getTeacherId());
        studentSignIn.setClassCode(classInfo.getCode());
        studentSignIn.setClassId(classId);
        studentSignIn.setStudentId(studentInfo.getId());
        studentSignIn.setSignInTime(new Date());
        studentSignIn.setCourseId(courseId);
        if (studentSignInDto.getLongitude() != null && studentSignInDto.getLatitude() != null) {
            studentSignIn.setSignInAddress(LongitudeAndLatitudeToAddress.getAddressByJWD(studentSignInDto.getLongitude(), studentSignInDto.getLatitude()));
        }
        StudentSignIn signIn = studentSignInService.saveNew(studentSignIn);
        return ResponseResult.success(signIn.getId());
    }

    /**
     * 学生账号获取签到列表
     * @return
     */
    @GetMapping("/getCourseInfoSignByStudentId")
    public ResponseResult<List<CourseInfo>> getCourseInfoSignByStudentId() {
        String errorMessage;
        TokenData tokenData = TokenData.takeFromRequest();
        StudentInfo studentInfo = studentInfoService.getStudentInfoByUserId(tokenData.getUserId());

        if (studentInfo == null) {
            errorMessage = "账户异常";
            return ResponseResult.error(ErrorCodeEnum.DATA_NOT_EXIST, errorMessage);
        }
        List<CourseInfo> courseInfoList =
                courseInfoService.getCourseInfoByClassId(studentInfo.getClassId());
        for (int i = 0; i < courseInfoList.size(); i++) {
            ProfessorInfo professorInfo = professorInfoService.getById(courseInfoList.get(i).getProfessorId());
            courseInfoList.get(i).setProfessorInfo(professorInfo);
            StudentSignIn signIn = new StudentSignIn();
            signIn.setClassId(studentInfo.getClassId());
            signIn.setStudentId(studentInfo.getId());
            signIn.setCourseId(courseInfoList.get(i).getId());
            List<StudentSignIn> studentSignInList = studentSignInService.getStudentSignInList(signIn, "update_time DESC");
            if (studentSignInList.size() != 0) {
                courseInfoList.get(i).setIsSign(1);
                courseInfoList.get(i).setSignInAddress(studentSignInList.get(0).getSignInAddress());
                courseInfoList.get(i).setSignInTime(studentSignInList.get(0).getSignInTime());
            } else {
                courseInfoList.get(i).setIsSign(0);
            }
        }
        return ResponseResult.success(courseInfoList);
    }

    /**
     * 教师端获取签到列表
     * @param studentSignInDtoFilter
     * @return
     */
    @PostMapping("/listSignInByCourseId")
    public ResponseResult<List<StudentSignIn>> listSignInByCourseId(
            @MyRequestBody StudentSignInDto studentSignInDtoFilter) {
        StudentSignIn studentSignInFilter = MyModelUtil.copyTo(studentSignInDtoFilter, StudentSignIn.class);
        List<StudentSignIn> studentSignInList =
                studentSignInService.listSignInByCourseId(studentSignInFilter);
        for (int i = 0; i < studentSignInList.size(); i++) {
            StudentInfo studentInfo = studentInfoService.getById(studentSignInList.get(i).getStudentId());
            studentSignInList.get(i).setStudentInfo(studentInfo);
        }
        return ResponseResult.success(studentSignInList);
    }

    @GetMapping("/course/count")
    public ResponseResult<SignInDto> countSignInByCourseId(@RequestParam Long courseId) {
        SignInDto signInDto = studentSignInService.countSignInByCourseId(courseId);
        CourseInfo courseInfo = courseInfoService.getById(courseId);
        ClassInfo classInfo = classInfoService.getById(courseInfo.getClassId());
        List<StudentInfo> classStudentList = studentInfoService.getStudentInfoByClassId(classInfo.getId());
        signInDto.setCount(classStudentList.size());
        signInDto.setNoSignInCount(classStudentList.size() - signInDto.getSignInCount());
        return ResponseResult.success(signInDto);
    }

    @GetMapping("/course/noSignIn")
    public ResponseResult<List<StudentInfo>> noSignIn(@RequestParam Long courseId) {
        List<StudentInfo> signInList = studentSignInService.getSignInStudentInfo(courseId);
        CourseInfo courseInfo = courseInfoService.getById(courseId);
        ClassInfo classInfo = classInfoService.getById(courseInfo.getClassId());
        List<StudentInfo> classStudentList = studentInfoService.getStudentInfoByClassId(classInfo.getId());
        List<StudentInfo> noSignInList = classStudentList.stream().filter(studentInfo -> !signInList.contains(studentInfo)).collect(Collectors.toList());
        return ResponseResult.success(noSignInList);
    }
}
